package com.zl.tby.core.base.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author changpeng
 * @version 1.0
 * @since 2024/11/3 20:01
 */
public class FFmpegFrameGrabber {
    public static boolean captureFirstFrame(String videoUrl, String outputPath) {
        try {
            // FFmpeg 命令行，截取视频第一帧并输出为图片
            String ffmpegCmd = "ffmpeg -i %s -frames:v 1 %s";
            String cmd = String.format(ffmpegCmd, videoUrl, outputPath);

            // 使用ProcessBuilder执行FFmpeg命令
            ProcessBuilder builder = new ProcessBuilder("cmd", "/c", cmd);
            Process process = builder.start();

            // 读取并打印FFmpeg的输出信息，可以用于调试
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // 等待FFmpeg进程结束
            process.waitFor();
            System.out.println("First frame captured and saved to " + outputPath);
            return true;
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            System.err.println("Error capturing first frame");
            return false;
        }
    }

    public static boolean captureFirstFrameLinux(String videoUrl, String outputPath) {
        System.out.println("videoUrl: " + videoUrl);
        System.out.println("outputPath: " + outputPath);
        try {
            // 构建ffmpeg命令
            ProcessBuilder processBuilder = new ProcessBuilder(
                    "ffmpeg",
                    "-i", videoUrl, // 输入视频URL
                    "-frames:v", "10", // 仅抓取第一帧
                    "-f", "image2", // 输出格式为图片
                    "-y", outputPath // 输出文件路径
            );

            // 启动ffmpeg进程
            Process process = processBuilder.start();

            // 等待ffmpeg进程结束
            process.waitFor();

            System.out.println("First frame captured and saved to " + outputPath);
            return true;
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            System.err.println("Error capturing first frame");
            return false;
        }
    }

    public static void main(String[] args) {
        // 视频URL和输出图片路径
        String videoUrl = "http://175.44.137.60:12007/file/img/2024/9/13/10/kUEWchusIOmKpgTKyXgYN.mp4";
        String outputPath = "output.jpg";

        // 调用方法截取视频第一帧
        captureFirstFrame(videoUrl, outputPath);
    }
}
